<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="名称" prop="name">
        <el-input class="w500" v-model="form.name" placeholder="例如：测试"></el-input>
      </el-form-item>
      <el-form-item label="所属分类">
        <el-cascader class="w500" clearable v-model="cateIds" :options="tree" :props="defaultProps" change-on-select>
        </el-cascader>
      </el-form-item>
      <el-form-item label="描述介绍">
        <el-input class="w500" v-model="form.description"></el-input>
      </el-form-item>
      <el-form-item label="跳转地址" prop="jump_url">
        <el-input class="w500" v-model="form.jump_url" placeholder="例如：http://www.baidu.com"></el-input>
      </el-form-item>
      <el-form-item label="添加图片">
        <el-upload
          :action="upload_url"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-success="handleAvatarSuccess">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="form.status">
          <el-radio label="0">废弃</el-radio>
          <el-radio label="1">正常</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序" prop="order">
        <el-input class="w100" v-model="form.order" type="number"></el-input>
      </el-form-item>
      <el-form-item label="上架时间">
        <el-date-picker v-model="start_time" type="datetime" placeholder="选择日期时间"></el-date-picker>
      </el-form-item>
      <el-form-item label="下架时间">
        <el-date-picker v-model="end_time" type="datetime" placeholder="选择日期时间"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('form')">提交</el-button>
        <el-button @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  import notify from '@/tools/notify'
  import { UPLOAD_URL } from '@/config/const'

  export default {
    data () {
      return {
        dialogImageUrl: '',
        dialogVisible: false,
        form: {
          c_id: '',
          pic_id: '',
          name: '',
          description: '',
          relative_path: '',
          absolute_path: '',
          jump_url: '',
          order: '1',
          add_user_id: '',
          auditor_id: '',
          status: '1',
          audit_status: '',
          start_time: '',
          end_time: ''
        },
        start_time: '',
        end_time: '',
        defaultProps: {
          value: 'id',
          label: 'name',
          children: '_child'
        },
        cateIds: [],
        rules: {
          name: [
            {required: true, message: '请输入广告名称', trigger: 'blur'},
            {min: 2, message: '请输入广告名称', trigger: 'blur'},
            {max: 15, message: '请输入广告名称', trigger: 'blur'}
          ],
          jump_url: [
            {required: true, message: '请输入跳转地址', trigger: 'blur'}
          ]
        }
      }
    },
    computed: {
      ...mapState({
        cover: state => state.advert.cover,
        user: state => state.user.info,
        tree: state => state.advert.classTree
      }),
      upload_url () {
        return UPLOAD_URL
      }
    },
    created () {
      this.classTree()
    },
    methods: {
      // 获取广告分类树
      async classTree () {
        await this.$store.dispatch('advert/classTree')
      },
      onSubmit (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (Number(this.cateIds.length) <= 0) {
              notify.warning('请选择广告分类!')
              return false
            }
            if (this.start_time !== '' || this.end_time !== '') {
              this.form.start_time = Date.parse(new Date(this.start_time)) / 1000
              this.form.end_time = Date.parse(new Date(this.end_time)) / 1000
              if (this.form.start_time >= this.form.end_time) {
                notify.warning('下架时间不能早于上架时间!')
              }
            }
            this.form.c_id = this.cateIds[Number(this.cateIds.length) - 1]
            this.form.add_user_id = this.user.id
            this.form.pic_id = this.cover.id
            this.form.relative_path = this.cover.relative_path + '/' + this.cover.filename
            this.form.absolute_path = 'http://' + this.cover.save_path + '/' + this.cover.filename
            this.$store.dispatch('advert/advertAdd', this.form).then(res => {
              notify.success(res.msg)
              this.$router.push('/advert/advertlist')
            })
          }
        })
      },
      handleAvatarSuccess (file, response, fileList) {
        const self = this
        if (file.code !== 200) {
          fileList.pop()
          notify.warning('封面上传失败')
        } else {
          notify.success('封面上传成功')
          self.$store.commit('advert/ADVERT_COVER', file.res)
        }
      },
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      goBack () {
        this.$nextTick(() => {
          this.$router.go(-1)
        })
      }
    }
  }
</script>
